<template>
  <div>
    <div>
      <div>
        <div style="height:100vh">
          <RelationGraph ref="graphRef" :options="graphOptions" @node-expand="onNodeExpand"
            @node-collapse="onNodeCollapse" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { defineComponent, ref, onMounted } from 'vue';
import { managelistApi } from '@/api/gplot'
import type { RGJsonData, RGOptions, RGNode, RGLine, RGLink, RGUserEvent, RelationGraphComponent } from 'relation-graph-vue3';
import RelationGraph from 'relation-graph-vue3';

const graphRef = ref<RelationGraphComponent | null>(null);
const graphOptions: RGOptions = {
  debug: false,
  layouts: [
    {
      layoutName: 'tree',
      from: 'top',
      min_per_width: 250,
      max_per_height: 200,
      max_per_width: 250,
      min_per_height: 130
    }
  ],
  allowShowMiniToolBar: false,
  disableDragNode: true,
  defaultNodeShape: 1,
  defaultLineShape: 4,
  defaultNodeBorderWidth: 0,
  defaultNodeColor: 'rgba(14, 192, 166, 1)',
  // defaultLineColor:'rgba(87, 152, 251, 1)',
  defaultJunctionPoint: 'tb'
};
function getQueryString(name:any)  {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  const search = window.location.search.split('?')[1] || '';
  const r = search.match(reg) || [];
  return r[2];
}
const res_nodes = ref([]);
const res_lines = ref([]);
const mainWidth = ref(0);
const urlParams = ref()

onMounted(() => {
  urlParams.value = {
    creditcode: decodeURIComponent(getQueryString('creditcode')),
    companyname: decodeURIComponent(getQueryString('companyname'))
  }
  uni.setNavigationBarTitle({ title: urlParams.value.companyname });
  mainWidth.value = urlParams.value.companyname.length * 18 + 50;
  managelistFn('11');
  managelistFn('12');
});
const arr_0: any = [];
const arr_1: any = [];
const managelistFn = (code: any) => {
  arr_0.push({
    id: urlParams.value.creditcode + '',
    html: `<div class="node-main" style="width:${mainWidth.value}px!important">${urlParams.value.companyname}</div>`
  });
  const params = {
    creditcode: urlParams.value.creditcode,
    companyname: urlParams.value.companyname,
    category: code
  };
  managelistApi(params).then((res: any) => {
    if (res?.code != 200 || !res.rows) return;
    res.rows.forEach((val: any, idx: any) => {
      if (code == '11') {
        arr_0.push({
          id: val.id + '',
          creditNo: val.creditNo,
          html: `<div class="node-top">${val.name}<br/>股权：${Number(val.percent).toFixed(2)}%</div>`,
          expandHolderPosition: val.hasChild ? 'top' : '',
          expanded: false,
          data: { isNeedLoadDataFromRemoteServer: true, childrenLoaded: false, creditNo: val.creditNo, code: code }
        });
        arr_1.push({
          from: val.id + '',
          to: urlParams.value.creditcode,
          showStartArrow: true,
          showEndArrow: false,
          color: "rgba(14, 192, 166, 1)"
        })
      } else {
        arr_0.push({
          id: val.id + '',
          creditNo: val.creditNo,
          html: `<div class="node-bottom">${val.name}<br/>股权：${Number(val.percent).toFixed(2)}%</div>`,
          expandHolderPosition: val.hasChild ? 'bottom' : '',
          expanded: false,
          data: { isNeedLoadDataFromRemoteServer: true, childrenLoaded: false, creditNo: val.creditNo, code: code }
        });
        arr_1.push({
          to: val.id + '',
          from: urlParams.value.creditcode + '',
          color: "rgba(22, 115, 255, 1)"
        })
      }
    })
    res_nodes.value = arr_0;
    res_lines.value = arr_1;
    console.log(res_nodes.value, res_lines.value)
    show();
  })
}

const show = async () => {
  const graph2 = graphRef.value;
  await resetGraph(graph2, 'graph2');
};

const resetGraph = async (graphRef: RelationGraphComponent | null, graphId: string) => {
  const __graph_json_data: RGJsonData = {
    rootId: 'P',
    nodes: res_nodes.value,
    lines: res_lines.value,
  };
  if (graphRef) {
    await showGraph(graphRef, __graph_json_data);
  }
};

const showGraph = async (graphRef: RelationGraphComponent, graph_json_data: RGJsonData) => {
  const graphInstance = graphRef.getInstance();
  await graphInstance.setJsonData(graph_json_data);
  await graphInstance.moveToCenter();
  await graphInstance.zoomToFit();
  await graphInstance.focusNodeById('a');
};

const onNodeCollapse = async (node: RGNode, $event: RGUserEvent) => {
  const graphInstance = graphRef.value!.getInstance();
  await graphInstance.doLayout();
};

const onNodeExpand = async (node: RGNode, $event: RGUserEvent) => {
  console.log('onNodeExpand:', node);
  const graphInstance = graphRef.value!.getInstance();
  if (!node.data.isNeedLoadDataFromRemoteServer) {
    console.log('These child nodes have already been loaded');
    await graphInstance.doLayout();
    return;
  }
  if (node.data.childrenLoaded) {
    console.log('These child nodes have already been loaded');
    await graphInstance.doLayout();
    return;
  }
  node.data.childrenLoaded = true;
  loadChildNodesFromRemoteServer(node, new_data => {
    const graphInstance = graphRef.value.getInstance();
    graphInstance.appendJsonData(new_data);
  });
};

const loadChildNodesFromRemoteServer = async (node: RGNode, callback: (new_data: RGJsonData) => void) => {
  const { creditNo, code } = node.data;
  console.log(creditNo, code, '请求接口....')
  const resData = await callbackApi(creditNo, code, node.id);
  // console.log()
  const _new_json_data: RGJsonData = resData;
  callback(_new_json_data);
};

const callbackApi = async (creditNo: any, code: any, nodeId: any) => {
  const params = {
    creditcode: creditNo,
    // companyname: urlParams.value.companyname,
    category: code
  };

  const arr_a: any = [];
  const arr_b: any = [];
  await managelistApi(params).then((res: any) => {
    if (res?.code != 200 || !res.rows) return;
    res.rows.forEach((val: any, idx: any) => {
      if (code == '11') {
        arr_a.push({
          id: val.id + '',
          creditNo: val.creditNo,
          html: `<div class="node-top">${val.name}<br/>股权：${Number(val.percent) ? Number(val.percent).toFixed(2) : val.percent}%</div>`,
          expandHolderPosition: val.hasChild ? 'top' : '',
          expanded: false,
          data: { isNeedLoadDataFromRemoteServer: true, childrenLoaded: false, creditNo: val.creditNo, code: code }
        });
        arr_b.push({
          from: val.id + '',
          to: nodeId,
          showStartArrow: true,
          showEndArrow: false,
          color: "rgba(14, 192, 166, 1)"
        })
      } else {
        arr_a.push({
          id: val.id + '',
          creditNo: val.creditNo,
          html: `<div class="node-bottom">${val.name}<br/>股权：${Number(val.percent) ? Number(val.percent).toFixed(2) : val.percent}%</div>`,
          expandHolderPosition: val.hasChild ? 'bottom' : '',
          expanded: false,
          data: { isNeedLoadDataFromRemoteServer: true, childrenLoaded: false, creditNo: val.creditNo, code: code }
        });
        arr_b.push({
          to: val.id + '',
          from: nodeId + '',
          color: "rgba(22, 115, 255, 1)"
        })
      }
    })
  })
  return {
    nodes: arr_a,
    lines: arr_b
  }
}
</script>

<style lang="scss"></style>

<style lang="scss" scoped>
::v-deep(.relation-graph) {
  .rel-map {
    background-size: 30px 30px;
    background-image: linear-gradient(90deg, rgba(0, 0, 0, 0.05) 1rpx, transparent 0), linear-gradient(180deg, rgba(0, 0, 0, 0.05) 1rpx, transparent 0);
  }

  .rel-node {
    display: flex;
    place-items: center;
    justify-content: center;
  }

  .rel-node-type-node {
    width: 150rpx;
    min-height: 40rpx;
    border-radius: 6rpx;
  }

  .node-top {
    width: 180rpx;
    height: 60rpx;
    border-radius: 6rpx;
    background-color: rgb(14, 192, 166);
    color: rgb(255, 255, 255);
    display: flex;
    place-items: center;
    justify-content: center;
    padding: 8rpx;
    box-sizing: border-box;
  }

  .node-bottom {
    width: 180rpx;
    height: 60rpx;
    border-radius: 6rpx;
    background-color: rgba(87, 152, 251, 1);
    color: rgb(255, 255, 255);
    display: flex;
    place-items: center;
    justify-content: center;
    padding: 8rpx;
    box-sizing: border-box;
  }

  .node-main {
    padding: 13rpx 14rpx;
    box-sizing: border-box;
    background-color: rgba(22, 115, 255, 1);
    font-family: Alibaba PuHuiTi;
    font-size: 18px;
    font-weight: 500;
    color: #ffffff;
    text-align: center;
    border-radius: 8rpx;
  }

  .c-expand-positon-bottom {
    margin-top: 21px;
  }

  .c-expand-positon-top .c-expanded {
    background: transparent url('../../assets/gplot/top-icon.png') no-repeat !important;
    background-size: 19px !important;
  }

  .c-expand-positon-top .c-collapsed {
    background: transparent url('../../assets/gplot/top-a-icon.png') no-repeat !important;
    background-size: 19px !important;
  }

  .c-expand-positon-bottom .c-expanded {
    background: #5798FB url('../../assets/gplot/bottom-icon.png') no-repeat !important;
    background-size: 19px !important;
  }

  .c-expand-positon-bottom .c-collapsed {
    background: #5798FB url('../../assets/gplot/bottom-a-icon.png') no-repeat !important;
    background-size: 19px !important;
  }

  .rel-node-peel {
    padding: 0 8px !important;
  }
}
</style>
